<template>
  <v-card class="mb-4" color="#424242">
    <v-card-title></v-card-title>

    <!-- 英语一每篇阅读难度分数 -->
    <div ref="english1Chart" style="width: 100%; height: 300px; margin-bottom: 20px;"></div>

    <!-- 英语二每篇阅读难度分数 -->
    <div ref="english2Chart" style="width: 100%; height: 300px; margin-bottom: 20px;"></div>

    <!-- 英语一、二历年总分对比 -->
    <div ref="yearlyCompareChart" style="width: 100%; height: 300px;"></div>
  </v-card>
</template>

<script>
import { ReadPrediction_results1Hdfs } from '@/api/job';
import { ReadPrediction_results2Hdfs } from '@/api/job';
import * as echarts from 'echarts';

export default {
  name: "PredictionLineChart",
  data() {
    return {
      english1Scores: [],
      english2Scores: [],
      loading: false,
      error: null,
      english1Chart: null,
      english2Chart: null,
      yearlyCompareChart: null,
    };
  },
  mounted() {
    this.initCharts();
    this.fetchData();
  },
  beforeDestroy() {
    if (this.english1Chart) {
      this.english1Chart.dispose();
      this.english1Chart = null;
    }
    if (this.english2Chart) {
      this.english2Chart.dispose();
      this.english2Chart = null;
    }
    if (this.yearlyCompareChart) {
      this.yearlyCompareChart.dispose();
      this.yearlyCompareChart = null;
    }
  },
  methods: {
    async fetchData() {
      this.loading = true;
      this.error = null;

      try {
        // 获取英语一数据
        const english1Response = await ReadPrediction_results1Hdfs();
        if (english1Response && english1Response.data.code === 200) {
          this.english1Scores = english1Response.data.data || [];
        }

        // 获取英语二数据
        const english2Response = await ReadPrediction_results2Hdfs();
        if (english2Response && english2Response.data.code === 200) {
          this.english2Scores = english2Response.data.data || [];
        }

        this.renderEnglish1Chart(); // 渲染英语一图表
        this.renderEnglish2Chart(); // 渲染英语二图表
        this.renderYearlyCompareChart(); // 渲染总分对比图表
      } catch (error) {
        this.error = {
          message: error.response?.data?.message || "请求失败，请检查网络"
        };
      } finally {
        this.loading = false;
      }
    },
    initCharts() {
      this.english1Chart = echarts.init(this.$refs.english1Chart);
      this.english2Chart = echarts.init(this.$refs.english2Chart);
      this.yearlyCompareChart = echarts.init(this.$refs.yearlyCompareChart);

      window.addEventListener('resize', () => {
        if (this.english1Chart) {
          this.english1Chart.resize();
        }
        if (this.english2Chart) {
          this.english2Chart.resize();
        }
        if (this.yearlyCompareChart) {
          this.yearlyCompareChart.resize();
        }
      });
    },
    renderEnglish1Chart() {
      if (!this.english1Chart) return;

      const xData = this.english1Scores.map(item => item.year);
      const yData = this.english1Scores.map(item => parseFloat(item.score));

      const option = {
        title: {
          text: '英语一每篇阅读难度分数',
          textStyle: {
            color: '#ffffff'
          }
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: xData,
          axisLabel: {
            rotate: 45
          },
          axisLine: {
            lineStyle: {
              color: '#ffffff'
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '分数',
          nameTextStyle: {
            color: '#ffffff'
          },
          axisLine: {
            lineStyle: {
              color: '#ffffff'
            }
          },
          splitLine: {
            lineStyle: {
              color: '#ffffff'
            }
          }
        },
        series: [
          {
            data: yData,
            type: 'line',
            symbol: 'circle',
            symbolSize: 8,
            itemStyle: {
              color: '#4CAF50' // 英语一颜色
            },
            lineStyle: {
              width: 2
            }
          }
        ]
      };

      this.english1Chart.setOption(option);
    },
    renderEnglish2Chart() {
      if (!this.english2Chart) return;

      const xData = this.english2Scores.map(item => item.year);
      const yData = this.english2Scores.map(item => parseFloat(item.score));

      const option = {
        title: {
          text: '英语二每篇阅读难度分数',
          textStyle: {
            color: '#ffffff'
          }
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: xData,
          axisLabel: {
            rotate: 45
          },
          axisLine: {
            lineStyle: {
              color: '#ffffff'
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '分数',
          nameTextStyle: {
            color: '#ffffff'
          },
          axisLine: {
            lineStyle: {
              color: '#ffffff'
            }
          },
          splitLine: {
            lineStyle: {
              color: '#ffffff'
            }
          }
        },
        series: [
          {
            data: yData,
            type: 'line',
            symbol: 'circle',
            symbolSize: 8,
            itemStyle: {
              color: '#2196F3' // 英语二颜色
            },
            lineStyle: {
              width: 2
            }
          }
        ]
      };

      this.english2Chart.setOption(option);
    },
    renderYearlyCompareChart() {
      if (!this.yearlyCompareChart) return;

      // 计算每年的总分
      const english1YearlyScores = this.calculateYearlyTotalScores(this.english1Scores);
      const english2YearlyScores = this.calculateYearlyTotalScores(this.english2Scores);

      // 创建一个包含两种考试的年份列表
      const combinedYears = [...new Set([...english1YearlyScores.map(item => item.year), ...english2YearlyScores.map(item => item.year)])]
          .sort((a, b) => parseInt(a) - parseInt(b));

      // 准备两个数组分别存储英语一和英语二的总分，没有数据的年份填入null
      const english1Data = combinedYears.map(year => {
        const score = english1YearlyScores.find(item => item.year === year);
        return score ? score.total : null;
      });

      const english2Data = combinedYears.map(year => {
        const score = english2YearlyScores.find(item => item.year === year);
        return score ? score.total : null;
      });

      const option = {
        title: {
          text: '英语一、二历年阅读难度总分对比',
          textStyle: {
            color: '#ffffff'
          }
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['英语一', '英语二'],
          textStyle: {
            color: '#ffffff'
          }
        },
        xAxis: {
          type: 'category',
          data: combinedYears,
          axisLabel: {
            rotate: 45
          },
          axisLine: {
            lineStyle: {
              color: '#ffffff'
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '总分',
          nameTextStyle: {
            color: '#ffffff'
          },
          axisLine: {
            lineStyle: {
              color: '#ffffff'
            }
          },
          splitLine: {
            lineStyle: {
              color: '#ffffff'
            }
          }
        },
        series: [
          {
            name: '英语一',
            data: english1Data,
            type: 'line',
            symbol: 'circle',
            symbolSize: 8,
            itemStyle: {
              color: '#4CAF50' // 英语一颜色
            },
            lineStyle: {
              width: 2
            }
          },
          {
            name: '英语二',
            data: english2Data,
            type: 'line',
            symbol: 'circle',
            symbolSize: 8,
            itemStyle: {
              color: '#2196F3' // 英语二颜色
            },
            lineStyle: {
              width: 2
            }
          }
        ]
      };

      this.yearlyCompareChart.setOption(option);
    },
    calculateYearlyTotalScores(scores) {
      const yearlyScores = {};

      for (const item of scores) {
        const year = item.year.substring(0, 4); // 提取年份部分
        const score = parseFloat(item.score);

        if (!yearlyScores[year]) {
          yearlyScores[year] = {
            year: year,
            total: 0
          };
        }

        yearlyScores[year].total += score;
      }

      return Object.values(yearlyScores).sort((a, b) => a.year - b.year);
    }
  }
};
</script>

<style scoped>
.v-card {
  box-shadow: 0 4px 4px rgba(0, 0, 0, 0.2);
}

.v-card-title {
  color: white;
}
</style>